package com.gancp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.gancp.common.constants.Parmeters;
import com.gancp.service.SendMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author gancp
 * @Date 时间被黑洞吸走了
 * @Descripition 秒滴短信发送
 **/
@Service
@Slf4j
public class MiaoDiSendMessageImpl implements SendMessage {
    @Autowired
    private Parmeters parmeters;

    private String dateFormmat = "yyyyMMddHHmmss";


    @Override
    public void sendVerifvCode(String phone, String verifyCode) throws Exception {
        Map map = buildParams( phone, verifyCode );
        JSONObject json = sendMessage( map );
        log.info( "手机号【" + phone + "】" + "验证码【" + verifyCode + "】发送成功," + "返回Json消息" + json );
    }

    private JSONObject sendMessage(Map params) throws Exception {
        try {
            String url = parmeters.getMiaodiMsgUrl();
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost request = new HttpPost();
            request.setURI( new URI( url ) );
            request.setHeader( "Content-type", "application/x-www-form-urlencoded" );
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            for (Iterator iter = params.keySet().iterator(); iter.hasNext(); ) {
                String name = (String) iter.next();
                String value = String.valueOf( params.get( name ) );
                nvps.add( new BasicNameValuePair( name, value ) );
            }
            request.setEntity( new UrlEncodedFormEntity( nvps, HTTP.UTF_8 ) );
            HttpResponse response = httpClient.execute( request );
            int code = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString( entity, "UTF-8" );
            JSONObject json = JSONObject.parseObject( result );
            if (!"00000".equals( json.get( "respCode" ) )) {
                throw new Exception( "" );
            }
            return json;
        } catch (Exception e) {
            log.error( "短信验证码发送失败", e );
            throw new Exception( "短信验证码发送失败" );
        }
    }

    private Map buildParams(String phoneNumber, String verifyCode) throws Exception {

        String accountSid = parmeters.getMiaodiMsgAccountSid();
        String acountToken = parmeters.getMiaodiMsgAcountToken();
        if (StringUtils.isBlank( accountSid ) || StringUtils.isBlank( acountToken )) {
            throw new Exception( "秒滴短信平台开发者账户不完整" );
        }
        Map map = new HashMap();
        map.put( "accountSid", accountSid );
        map.put( "smsContent", "【疾风剑豪】登录验证码：{" + verifyCode + "}，爱用不用。 --来自gcp的小尾巴" );
        map.put( "to", phoneNumber );
        String date = new SimpleDateFormat( dateFormmat ).format( new Date() );
        map.put( "timestamp", date );
        String sig = DigestUtils.md5Hex( accountSid.concat( acountToken ).concat( date ) );
        map.put( "sig", sig );
        return map;
    }


}
